package softtech.apps.autoanswerphonecall;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Environment;

public class DatabaseHandler extends SQLiteOpenHelper {

	private static final String LOG = DatabaseHandler.class.getName();
	// All Static variables
	// Database Version
	private static final int DATABASE_VERSION = 12;

	// Database Name
	private static final String DATABASE_NAME = "autoAnswerPhoneCallManager";

	// Messages table name
	private static final String TABLE_MESSAGES = "messages";
	private static final String TABLE_CONFIGS = "configs";
	
	
	// Messages Table Columns names
	private static final String KEY_ID = "id";
	private static final String KEY_NAME = "message";
	private static final String KEY_IS_CHOOSE = "is_choose";
	

	// Configs Table Column names
	private static final String CONFIG_KEY_ID = "id";
	private static final String CONFIG_KEY_VALUE = "value";
	private static final String CONFIG_KEY_WORD = "keyword";

	Context myContext;
	private static String DB_PATH = "";

	private final String CREATE_MESSAGES_TABLE = "CREATE TABLE "
			+ TABLE_MESSAGES + "(" + KEY_ID + " INTEGER PRIMARY KEY,"
			+ KEY_NAME + " TEXT," + KEY_IS_CHOOSE + " INTEGER)";

	private final String CREATE_CONFIGS_TABLE = "CREATE TABLE " + TABLE_CONFIGS
			+ "(" + CONFIG_KEY_ID + " INTEGER PRIMARY KEY," + CONFIG_KEY_VALUE
			+ " INTEGER,"+ CONFIG_KEY_WORD +" TEXT)";
	
	
	

	public DatabaseHandler(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
		this.myContext = context;

		if (android.os.Build.VERSION.SDK_INT >= 4.2) {
			DB_PATH = myContext.getApplicationInfo().dataDir + "/databases/";
		} else {
			DB_PATH = "/data/data/" + myContext.getPackageName()
					+ "/databases/";
		}

		/*
		 * DB_PATH = Environment.getDataDirectory().getPath() + "/data/" +
		 * myContext.getPackageName() + "/databases/";
		 */
	}
	 @Override
	    public void onCreate(SQLiteDatabase db) {
	 
	        // creating required tables
	        db.execSQL(CREATE_MESSAGES_TABLE);
	        db.execSQL(CREATE_CONFIGS_TABLE);
	        db.execSQL("INSERT INTO " + TABLE_CONFIGS + "(" + CONFIG_KEY_VALUE + ","+CONFIG_KEY_WORD+") values(0,1)"); // enable mode
	        db.execSQL("INSERT INTO " + TABLE_CONFIGS + "(" + CONFIG_KEY_VALUE + ","+CONFIG_KEY_WORD+") values(0,2)"); // voice mode
	        db.execSQL("INSERT INTO " + TABLE_CONFIGS + "(" + CONFIG_KEY_VALUE + ","+CONFIG_KEY_WORD+") values(1,3)"); // sms mode
	        db.execSQL("INSERT INTO " + TABLE_CONFIGS + "(" + CONFIG_KEY_VALUE + ","+CONFIG_KEY_WORD+") values(-1,4)"); // audio value
	        db.execSQL("INSERT INTO " + TABLE_CONFIGS + "(" + CONFIG_KEY_VALUE + ","+CONFIG_KEY_WORD+") values(1,5)"); // record message
	        db.execSQL("INSERT INTO " + TABLE_CONFIGS + "(" + CONFIG_KEY_VALUE + ","+CONFIG_KEY_WORD+") values(0,6)"); // max duration choice
	        
	        /**
	         * 1 = enable
	         * 2 = Voice
	         * 3 = SMS
	         * 4 = index of audio file
	         * */
	        db.execSQL("INSERT INTO " + TABLE_MESSAGES + "(" + KEY_NAME + "," + KEY_IS_CHOOSE + ") values('Im busy now, ill call you later',1)");
	    }
	 
	    @Override
	    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
	        // on upgrade drop older tables
	        db.execSQL("DROP TABLE IF EXISTS " + TABLE_MESSAGES);
	        db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONFIGS);
	 
	        // create new tables
	        onCreate(db);
	    }

	/**
	 * All CRUD(Create, Read, Update, Delete) Operations
	 */

	// Adding new contact
	void addMessage(Message message) {
		SQLiteDatabase db = this.getWritableDatabase();

		ContentValues values = new ContentValues();
		values.put(KEY_NAME, message.get_message()); 
		values.put(KEY_IS_CHOOSE, message.get_is_choose());
		// Inserting Row
		db.insert(TABLE_MESSAGES, null, values);
		db.close(); // Closing database connection
	}

	// Getting single contact
	Message getMessage(int id) {
		SQLiteDatabase db = this.getReadableDatabase();

		Cursor cursor = db.query(TABLE_MESSAGES, new String[] { KEY_ID,
				KEY_NAME }, KEY_IS_CHOOSE + "=?", new String[] { String.valueOf(id) },
				null, null, null, null);
		if (cursor != null)
			cursor.moveToFirst();

		Message message = new Message(Integer.parseInt(cursor.getString(0)),
				cursor.getString(1), Integer.parseInt(cursor.getString(2)));
		// return contact
		db.close();
		return message;
	}

	// Getting message with is_choose = 1;
	// Getting single contact
	public Message getMessageChoose(int id) {
		SQLiteDatabase db = this.getReadableDatabase();
		
		Cursor cursor = db.query(TABLE_MESSAGES, new String[] { KEY_ID,
				KEY_NAME }, KEY_IS_CHOOSE + "=?", new String[] { String.valueOf(id) },
				null, null, null, null);
		if (cursor != null)
			cursor.moveToFirst();

		Message message = new Message(Integer.parseInt(cursor.getString(0)),
				cursor.getString(1), Integer.parseInt(cursor.getString(2)));
		// return message
		db.close();
		return message;
	}
	// Getting All Contacts
	public List<Message> getAllMessages() {
		List<Message> messageList = new ArrayList<Message>();
		// Select All Query
		String selectQuery = "SELECT  * FROM " + TABLE_MESSAGES;

		SQLiteDatabase db = this.getWritableDatabase();

		if (db.equals(null) || db == null) {
			return null;
		}

		Cursor cursor = db.rawQuery(selectQuery, null);

		// looping through all rows and adding to list
		if (cursor.moveToFirst()) {
			do {
				Message message = new Message();
				message.set_id((Integer.parseInt(cursor.getString(0))));
				message.set_message((cursor.getString(1)));
				message.set_is_choose((Integer.parseInt(cursor.getString(2))));
				messageList.add(message);
			} while (cursor.moveToNext());
		}

		// return contact list
		db.close();
		return messageList;
	}
	
	public int updateMessage(Message message) {
	    SQLiteDatabase db = this.getWritableDatabase();
	 
	    ContentValues values = new ContentValues();
	    values.put(KEY_NAME, message.get_message());
		values.put(KEY_IS_CHOOSE, message.get_is_choose());
	 
	    // updating row
		int temp = db.update(TABLE_MESSAGES, values, KEY_ID + " = ?",
	            new String[] { String.valueOf(message.get_id()) });
		db.close();
	    return temp;
	    
	}
	
	// Update is choose
	
	public int updateMessageChoose(int id) {
	    SQLiteDatabase db = this.getWritableDatabase();
	 
	    ContentValues values = new ContentValues();
		values.put(KEY_IS_CHOOSE, 0);
	    // updating row
		int temp = db.update(TABLE_MESSAGES, values, KEY_ID + " = ?",
	            new String[] { String.valueOf(id) });
		db.close();
	    return temp;
	}

	// Deleting single contact
	public void deleteMessage(Message message) {
		SQLiteDatabase db = this.getWritableDatabase();
		db.delete(TABLE_MESSAGES, KEY_ID + " = ?",
				new String[] { String.valueOf(message.get_id()) });
		db.close();
	}

	// Getting contacts Count
	public int getMessagesCount() {
		String countQuery = "SELECT  * FROM " + TABLE_MESSAGES;
		SQLiteDatabase db = this.getReadableDatabase();
		Cursor cursor = db.rawQuery(countQuery, null);
		cursor.close();

		// return count
		db.close();
		return cursor.getCount();
	}

	// Update config
	public int updateConfig(Config config) {
		SQLiteDatabase db = this.getWritableDatabase();

		ContentValues values = new ContentValues();
		values.put(CONFIG_KEY_VALUE, config.get_value());
		// updating row
		int temp = db.update(TABLE_CONFIGS, values, CONFIG_KEY_ID + " = ?",
				new String[] { String.valueOf(config.get_id()) });
				db.close();
	    return temp;
	}

	// Select config
	Config getConfig(int pos) {
		SQLiteDatabase db = this.getReadableDatabase();
		Cursor cursor = db.query(TABLE_CONFIGS,
				new String[] { CONFIG_KEY_ID,CONFIG_KEY_VALUE,CONFIG_KEY_WORD }, CONFIG_KEY_WORD + "=?",
				new String[] {  String.valueOf(pos) }, null, null, null, null);
		if (cursor != null)
			cursor.moveToFirst();

		Config config = new Config(Integer.parseInt(cursor.getString(0)),
				Integer.parseInt(cursor.getString(1)),Integer.parseInt(cursor.getString(2)));
		// return message
		db.close();
		return config;
	}

	// Getting All config
	public List<Config> getAllConfigs() {

		//Log.d("CONFIG", "Bat dau truy van");

		List<Config> configList = new ArrayList<Config>();
		// Select All Query
		String selectQuery = "SELECT  * FROM " + TABLE_CONFIGS;

		try {
			SQLiteDatabase db = this.getWritableDatabase();
			Cursor cursor = db.rawQuery(selectQuery, null);

			// looping through all rows and adding to list
			if (cursor.moveToFirst()) {
				do {
					Config config = new Config();
					config.set_id((Integer.parseInt(cursor.getString(0))));
					config.set_value(Integer.parseInt(cursor.getString(1)));
					config.set_keyword(Integer.parseInt(cursor.getString(2)));
					// Adding contact to list
					configList.add(config);
				} while (cursor.moveToNext());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		// return contact list
		return configList;
	}

}
